package com.ilancuo.java8.optional;

import java.util.HashMap;
import java.util.Optional;

public class OptionalTest {
    public static void main(String[] args) {
        HashMap<Integer, User> userHashMap = new HashMap<Integer, User>();
        userHashMap.put(1, new User(1, "Xiao Ming"));
        userHashMap.put(2, new User(2, "Xiao Zhi"));
        userHashMap.put(3, null);

        UserUtil userUtil = new UserUtil(userHashMap);
        // orElse
        User user = Optional.ofNullable(UserUtil.getUserByUserId(2))
                .orElse(new User(1, "Xiao Bai"));

        // orElseGet
        User user1 = Optional
                .ofNullable(UserUtil.getUserByUserId(2))
                .orElseGet(() -> new User(1, "Xiao Bai"));

        User user2 = Optional
                .ofNullable(UserUtil.getUserByUserId(2))
                .orElseThrow(() -> new AssertionError("AssertionError"));

        String userName = Optional
                .ofNullable(UserUtil.getUserByUserId(1))
                .map(user3 -> user3.name)
                .map(String::toLowerCase)
                .orElse("123");
    }
}
